<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\room;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsExcelInterface;
use app\common\model\Device;
use app\common\model\room\RoomHospital;
use app\common\model\room\RoomHospitalDevice;
use app\common\model\room\RoomHospitalDeviceLog;
use app\common\lists\ListsSearchInterface;
use app\common\model\room\RoomHospitalLog;


/**
 * 全院设备记录列表
 * Class RoomHospitalDeviceLogLists
 * @package app\adminapi\listsroom
 */
class RoomHospitalDeviceLogLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface {


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function setSearch(): array {
        return [
//            '=' => ['cid', 'rid', 'device_id', 'coefficient', 'price', 'base_number', 'reading', 'use_total', 'lift_fee', 'second_pressure_fee', 'total_fee'],
//            'between_time' => ['log_time'],
        ];
    }

    public function queryWhere() {
        $param = $this->request->param();
        $where = [];

        if (!empty($this->adminCid) && $this->adminCid !== 0) {
            $where[] = ['cid', '=', $this->adminCid];
        }

        if (!empty($param['cb_ids'])) {
            if (!empty($param['cb_ids'][0])) {
                $where[] = ['cid', '=', $param['cb_ids'][0]];
            }
            if (!empty($param['cb_ids'][1])) {
                $where[] = ['bid', '=', $param['cb_ids'][1]];
            }
        }

        if (isset($param['room_keyword']) && $param['room_keyword'] != '') {
            $room_ids = RoomHospital::where([
                ['name|address', 'like', '%' . $param['room_keyword'] . '%']
            ])->column("id");
            $where[] = ['id', 'in', $room_ids];
        }

        if (isset($param['room_type']) && $param['room_type'] != '') {
            $room_ids = RoomHospital::where([
                ['type', '=', $param['room_type']]
            ])->column("id");
            $where[] = ['id', 'in', $room_ids];
        }

        if (isset($param['user_keyword']) && $param['user_keyword'] != '') {
            $where[] = ['user_name|user_mobile', 'like', '%' . $param['user_keyword'] . '%'];
        }

//        if (isset($param['device_keyword']) && $param['device_keyword'] != '') {
//            $device_ids = Device::where([
//                ['name|device_no', 'like', '%' . $param['device_keyword'] . '%']
//            $where[] = ['device_id', 'in', $device_ids];
//            ])->column("id");
//        }
        if (isset($param['device_keyword']) && $param['device_keyword'] != '') {
            $where[] = ['device_name|device_no', 'like', '%' . $param['device_keyword'] . '%'];
        }
        if (isset($param['start_time']) && $param['start_time'] != '') {
            $where[] = ['log_time', '>=', $param['start_time']];
        }
        if (isset($param['end_time']) && $param['end_time'] != '') {
            $where[] = ['log_time', '<=', $param['end_time']];
        }

        return $where;
    }

    public function get_query() {
        $this_month = date("Ym");

        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");

        if ($this_month == $search_month) {
            return RoomHospital::field([
                "*", "'" . $search_month . "' as log_date",
            ])->where($this->queryWhere());
        }

        return RoomHospitalLog::field([
            "*",
        ])->where($this->queryWhere())->where("log_date", $search_month);
    }

    public function query_append($query, $is_page = 1) {
        $query = $query
            ->append([
                "sort",
            ])
            ->with([
                "campus", "building", // "allDevice",
            ])
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_use_total';
                $query->where('device_type', 1);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_price';
                $query->where('device_type', 1);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_total_fee';
                $query->where('device_type', 1);
            }], "total_fee")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_use_total';
                $query->where('device_type', 2);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_price';
                $query->where('device_type', 2);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_total_fee';
                $query->where('device_type', 2);
            }], "total_fee")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_all_total_fee';
            }], "total_fee");
        if ($is_page == 1) {
            $query->limit($this->limitOffset, $this->limitLength);
        }
        return $query->order([
            'sort' => 'asc', 'id' => 'asc'
        ])->select()->each(function (&$item) {
            $item->room_s_use_total = $item->room_s_use_total * 1;
            $item->room_s_price = $item->room_s_price * 1;
            $item->room_s_total_fee = $item->room_s_total_fee * 1;

            $item->room_d_use_total = $item->room_d_use_total * 1;
            $item->room_d_price = $item->room_d_price * 1;
            $item->room_d_total_fee = $item->room_d_total_fee * 1;

            $item->room_all_total_fee = 1 * sprintf("%.2f", array_sum([
                    $item['room_all_total_fee'], $item['lift_fee'], $item['second_pressure_fee'],
                ]));

            $item->room_lift_fee = $item->lift_fee * 1;
            $item->room_second_pressure_fee = $item->second_pressure_fee * 1;

            if (is_string($item['user'])) {
                $item_user = json_decode($item['user'], true);
                $item->user = $item_user;
                $item->user_name = $item_user[0]['user_name'];
                $item->user_mobile = $item_user[0]['user_mobile'];
            }

            return $item;
        })->toArray();
    }

    /**
     * @notes 获取全院设备记录列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function lists(): array {
        return $this->query_append($this->get_query(), 1);
    }

    /**
     * @notes 获取全院设备记录数量
     * @return int
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function count(): int {
        return $this->get_query()->count();
    }

    public function print_lists() {
        return $this->query_append($this->get_query(), 0);
    }

    /**
     * @notes 导出文件名
     * @return string
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setFileName(): string {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");

        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);

        $m_arr = [];
        $m_arr['01'] = "01-02-03月";
        $m_arr['02'] = "01-02-03月";
        $m_arr['03'] = "01-02-03月";
        $m_arr['04'] = "04-05-06月";
        $m_arr['05'] = "04-05-06月";
        $m_arr['06'] = "04-05-06月";
        $m_arr['07'] = "07-08-09月";
        $m_arr['08'] = "07-08-09月";
        $m_arr['09'] = "07-08-09月";
        $m_arr['10'] = "10-11-12月";
        $m_arr['11'] = "10-11-12月";
        $m_arr['12'] = "10-11-12月";

        return '全院住户信息表-' . $year . '年' . $m_arr[$month];
    }

    public function setExcelLists() {
        return null;
    }

    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array {
        return [
            'name' => '房间信息',
            'user_name' => '住户',
            'room_d_use_total' => '用电度数',
            'room_d_price' => '电单价',
            'room_d_total_fee' => '总电费',
            'room_s_use_total' => '用水度数',
            'room_s_price' => '水单价',
            'room_s_total_fee' => '总水费',
            'room_lift_fee' => '电梯费',
            'room_second_pressure_fee' => '二次加压费',
            'room_all_total_fee' => '总费用',
            'log_date' => '时间',
        ];
    }

}
